package com.itzh.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final  int PORT = 6667;

    public GroupChatServer(){
        try{
            //得到选择器
            selector = Selector.open();
            listenChannel =ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该listenChannel注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //监听
    public void listen(){
        try{
            while(true){
                int count = selector.select();
                if(count > 0){ //有事件处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();

                        //监听到accept
                        if(key.isAcceptable()){
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //将该 sc 注册到selector
                            sc.register(selector,SelectionKey.OP_READ);
                            //提示
                            System.out.println(sc.getRemoteAddress()+"上线");
                        }
                        if(key.isReadable()){
                            readData(key);
                        }
                        //当前的 key 删除
                        iterator.remove();
                    }
                }else{
                    System.out.println("等待.......");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            
        }
    }

    private void readData(SelectionKey key){
        SocketChannel channel = null;
        try{
            //得到channel
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);

            //根据count的值做处理
            if(count > 0){
                //把缓冲区的数据转成字符串
                String msg = new String(buffer.array());
                System.out.println("form 客户端："+msg);
                //向其他的客户端转发消息
                sendInfoToOtherClients(msg,channel);

            }

        }catch (Exception e){
            e.printStackTrace();
            try {
                System.out.println(channel.getRemoteAddress()+"离线了");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    //转发消息给其他的客户
    private void sendInfoToOtherClients(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中。。。。");
        //遍历 所有注册到selector 上的 SocketChannel 并排除self
        for(SelectionKey key:selector.keys()){
            Channel targetChannel = key.channel();
            //排除自己
            if(targetChannel instanceof  SocketChannel && targetChannel != self){
               SocketChannel dest = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }

}
